package com.eclipse.e20200131_模拟连接池.com.qf.app1.m4;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import java.util.concurrent.TimeUnit;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;


public class Test2 {
	private static Logger logger = LogManager.getLogger();

	// 池化
	private static List<Connection> pool = new ArrayList<>();

	private static Properties config = new Properties();

	private static String diverclass = null;

	private static String url = null;

	private static String userName = null;

	private static String password = null;

	// 记载配置文件，读取jdbc的配置信息
	static {
		try {
			config.load(JDBCUtils.class.getClassLoader().getResourceAsStream("config.properties"));
			url = config.getProperty("jdbc.url");
			userName = config.getProperty("jdbc.username");
			password = config.getProperty("jdbc.password");
			diverclass = config.getProperty("jdbc.diverclass");
		} catch (Exception ex) {
			ex.printStackTrace();
			logger.error(ex);
		}
	}

	static {
		for (int i = 0; i < 5; i++) {
			// 1:加载驱动类
			try {
				Class.forName(diverclass);

				// 2: 打开连接
				Connection connection = DriverManager.getConnection(url, userName, password);
				pool.add(connection);
			} catch (Exception e) {
				logger.fatal(e);
			}

		}
	}

	public static void main(String[] args) throws Exception {
		//测试连接所花费的纳秒数
		long start = System.nanoTime();
		for (int i = 0; i < 100; i++) {
			Connection connection1 = getConnection2();
			closeConnection(connection1);
		}
		logger.debug(System.nanoTime() - start);

	}

	/**
	 * 把连接还给list
	 * 
	 * @param connection
	 */
	public static void closeConnection(Connection connection) {
		pool.add(connection);
	}

	/**
	 * 打开连接
	 * 
	 * @return
	 * @throws Exception
	 */
	public static Connection getConnection2() {
		//返回并且删除
		if (pool.size() > 0) {
			return pool.remove(pool.size() - 1);
		} else {
			try {
				//获取当前线程 睡觉1秒
				TimeUnit.SECONDS.sleep(1);
			} catch (InterruptedException e) {
				logger.warn(e);
			}
			//睡觉1秒后 再次获取
			return pool.remove(pool.size() - 1);
		}
	}

	/**
	 * 打开连接
	 * 
	 * @return
	 * @throws Exception
	 */
	public static Connection getConnection1() {
		try {
			// 1:加载驱动类
			Class.forName(diverclass);

			// 2: 打开连接
			Connection connection = DriverManager.getConnection(url, userName, password);
			return connection;
		} catch (ClassNotFoundException ex) {
			throw new RuntimeException("数据库驱动没导入", ex);
		} catch (SQLException ex) {
			throw new RuntimeException("url或者用户名或者密码是错误", ex);
		}
	}

}
